import os
import subprocess
from pdf2image import convert_from_path
from fastapi import HTTPException
def pptx_to_pdf(pptx_path, pdf_path):
    """Convert a .pptx file to .pdf using LibreOffice command line."""
    try:
        # Ensure the output directory exists
        os.makedirs(os.path.dirname(pdf_path), exist_ok=True)

        # Use LibreOffice to convert pptx to pdf
        subprocess.run(
            ['soffice', '--headless', '--convert-to', 'pdf', '--outdir', os.path.dirname(pdf_path), pptx_path],
            check=True)
        print(f"Converted {pptx_path} to {pdf_path}")
    except subprocess.CalledProcessError as e:
        print(f"Failed to convert {pptx_path} to PDF: {e}")

def pdf_to_images(pdf_path, output_folder, max_pages=None):
    """Convert each page of a PDF into an image and save them in the specified folder."""
    # Ensure the output directory exists
    os.makedirs(output_folder, exist_ok=True)

    # Convert PDF pages to images
    images = convert_from_path(pdf_path)

    # Apply the max_pages limit
    if max_pages is not None and len(images) > max_pages:
        raise HTTPException(status_code=400, detail=f"本示例应用建议上传的pptx在{max_pages}页以内，以便快速体验效果")

    for i, image in enumerate(images):
        image.save(os.path.join(output_folder, f"slide_{i + 1}.png"), "PNG")
        print(f"Saved slide_{i + 1}.png")

def pptx_to_images(pptx_path, output_folder, max_pages=None):
    """Convert a .pptx file to images of each slide."""
    # Extract the base name of the pptx file without extension
    base_name = os.path.splitext(os.path.basename(pptx_path))[0]
    # Create the pdf path using the base name
    pdf_path = os.path.join(output_folder, f"{base_name}.pdf")

    try:
        # Convert pptx to pdf
        pptx_to_pdf(pptx_path, pdf_path)

        # Convert pdf to images with max_pages limit
        pdf_to_images(pdf_path, output_folder, max_pages=max_pages)
    finally:
        # Clean up temporary files
        if os.path.exists(pdf_path):
            os.remove(pdf_path)
